<template>
  <div>
    <div class="flex justify-between">
      <div
        class="back"
        style="cursor: pointer"
        @click="
          () => {
            $router.go(-1);
          }
        "
      >
        <i class="el-icon-arrow-left" /> {{ operatorName }}
      </div>
    </div>
    <el-card
      shadow="never"
      :body-style="{ padding: '0px' }"
      :page-size="pageSize"
      :total="rows"
      :current-page="pageNo"
      @current-change="currentChangeHandle"
    >
      <el-form class="p-4" inline :model="dataForm">
        <el-form-item>
          <el-select
            v-model="dataForm.statType"
            clearable
            :placeholder="$t('statistic.statType')"
          >
            <el-option
              v-for="item in _statTypes"
              :key="item"
              :value="item"
              :label="$t('contract_statistic.' + item)"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="dataForm.status"
            clearable
            :placeholder="$t('statistic.status')"
          >
            <el-option
              v-for="item in _statusList"
              :key="item"
              :value="item"
              :label="$t('statistic.statuslist.' + item)"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="w-8"
            @click="getStatisticDataList((pageNo = 1))"
          >
            <svg-icon icon-class="search" />
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="w-8"
            @click="regenerateAndRePushStatisticData"
            v-if="isAuth('10402002.MANAGE')"
          >
            <i class="el-icon-upload2" />
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="dataListLoading"
        :data="dataList"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" />
        <el-table-column prop="statType" :label="$t('statistic.statType')">
          <template v-slot="scope">
            {{ $t("contract_statistic." + scope.row.statType) }}
          </template>
        </el-table-column>
        <el-table-column prop="statValue" :label="$t('statistic.statValue')" />
        <el-table-column prop="status" :label="$t('statistic.status')">
          <template v-slot="scope">
            {{ $t("statistic.statuslist." + scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column width="75px">
          <template v-slot="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('common.downloadBtn')"
              placement="top"
            >
              <el-button
                text
                :disabled="
                  scope.row.filePath === undefined || scope.row.filePath === null
                "
                class="w-8"
                @click="downloadDetailFile(scope.row)"
                ><svg-icon icon-class="Download"
              /></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
import {
  getStatisticDataList,
  regenerateAndRePushStatisticData,
  regenerateStatisticData,
  rePushStatisticData,
} from "@/api/statistic-operator";
import axios from "axios";
import { getToken } from "@/utils/auth";
import store from "@/store";
import { isAuth } from "@/utils";

export default {
  data() {
    return {
      dataForm: {
        statType: [],
        status: "",
      },
      activeName: "first",
      operatorId: this.$route.query.operatorId,
      operatorName: this.$route.query.operatorName,
      year: this.$route.query.year,
      month: this.$route.query.month,
      platCode: this.$route.query.platCode,
      dataList: [],
      pageNo: 1,
      pageSize: 10,
      rows: 0,
      statTypeList: [],
      dataListLoading: false,
      selectedData: [],
    };
  },
  computed: {
    _statTypes() {
      var statObj = this.$t("contract_statistic");
      const statTyeList = Object.keys(statObj);
      // console.log(statTyeList)
      return statTyeList;
    },
    _statusList() {
      var statusObj = this.$t("statistic.statuslist");
      const statusList = Object.keys(statusObj);
      // console.log(statusList)
      return statusList;
    },
  },
  mounted() {
    if (this.operatorId) {
      this.getStatisticDataList();
    } else {
      this.$router.push({ path: "/404" });
    }
  },
  methods: {
    isAuth,
    getStatisticDataList() {
      this.dataListLoading = true;
      const ids = [];
      ids.push(this.operatorId);
      const statTypes = [];
      if (this.dataForm.statType !== "") {
        statTypes.push(this.dataForm.statType);
      }
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        year: this.year,
        month: this.month,
        keyIds: ids,
        statTypes: statTypes,
        status: this.dataForm.status,
        characterCode: "OPERATOR",
        platCode: this.platCode,
      };
      getStatisticDataList(params)
        .then((res) => {
          this.dataList = res.list;
          this.rows = res.total;
          this.dataListLoading = false;
        })
        .catch((e) => {
          this.dataListLoading = false;
          this.$confirmError(e);
        });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageNo = 1;
      this.getStatisticDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNo = val;
      this.getStatisticDataList();
    },
    handleSelectionChange(val) {
      this.selectedData = val;
    },
    regenerateStatisticData() {
      const statTypes = [];
      this.selectedData.forEach((item) => {
        statTypes.push(item.statType);
      });
      const ids = [];
      ids.push(this.operatorId);
      var data = {
        year: this.year,
        month: this.month,
        statTypes: statTypes,
        keyIds: ids,
        characterCode: "OPERATOR",
      };
      regenerateStatisticData(data)
        .then(() => {
          this.$message.success(this.$t("statistic.success"));
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    rePushStatisticData() {
      const statTypes = [];
      console.log(JSON.stringify(this.selectedData));
      this.selectedData.forEach((item) => {
        statTypes.push(item.statType);
      });
      const ids = [];
      ids.push(this.operatorId);
      var data = {
        year: this.year,
        month: this.month,
        statTypes: statTypes,
        keyIds: ids,
        characterCode: "OPERATOR",
      };
      rePushStatisticData(data)
        .then(() => {
          this.$message.success(this.$t("statistic.success"));
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    regenerateAndRePushStatisticData() {
      this.$confirm(this.$t("statistic.regenarate_repush_confirm"), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "info",
      }).then(() => {
        const statTypes = [];
        console.log(JSON.stringify(this.selectedData));
        this.selectedData.forEach((item) => {
          statTypes.push(item.statType);
        });
        const ids = [];
        ids.push(this.operatorId);
        var data = {
          year: this.year,
          month: this.month,
          statTypes: statTypes,
          keyIds: ids,
          characterCode: "OPERATOR",
          platCode: this.platCode,
        };
        regenerateAndRePushStatisticData(data)
          .then(() => {
            this.$message.success(this.$t("statistic.success"));
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      });
    },
    downloadDetailFile(row) {
      const fileArray = row.filePath.split("/");
      console.log(fileArray[fileArray.length - 1]);
      this.downLoad(
        import.meta.env.VITE_APP_BASE_API +
          "/online/statistic-report/statistic/report/file/export/",
        fileArray[fileArray.length - 1],
        {
          recordId: row.statUuid,
          month: Number(this.$route.query.month),
        }
      );
    },
    downLoad(url, fileName, params) {
      axios({
        method: "get",
        url: url,
        responseType: "blob",
        headers: {
          "WEB-TOKEN": getToken(),
          LANG:
            // eslint-disable-next-line no-undef
            localStorage.getItem(store.state.user.keys.storage.lang) || "en-US",
        },
        params: params,
      })
        .then(({ data }) => {
          if (data) {
            var url = window.URL.createObjectURL(data);
            var a = document.createElement("a");
            a.href = url;
            a.download = fileName;
            a.click();
          } else {
            this.$message.error("Download error");
          }
        })
        .catch(this.$confirmError);
    },
  },
};
</script>
